import Tosat from './toast.vue'

let ToastConstructor, Vue

/**
 * 关闭
 */
function onClose() {
    this.$el.addEventListener('transitionend', () => {
        let node = this.$el
        if (node) {
            node.parentNode.removeChild(node)
        }
        
        // 销毁实例
        setTimeout(() => {
            this.$destroy()
        }, 1000)
    })
}

export let option = {}

/**
 * 显示 toast
 * @param {Object} options 
 */
function toast(options = {}) {
    let opt = Object.assign({}, option, typeof options == 'string' ? {message: options} : options)
    // 延时关闭toast
    let duration = opt.duration || 3000;
    var toast = new ToastConstructor({
        el: document.createElement('div')
    })

    Object.assign(toast, opt)

    toast.$on('close', onClose)

    document.body.appendChild(toast.$el)

    Vue.nextTick(function () {
        toast.visible = true
        if(~duration){
            setTimeout(function () {
                toast.close()
            }, duration)
        }
    })
    return toast
}

/**
 * 全局插件形式注册组件
 * @param {Vue} vue 
 * @param {String} toastName 
 */
export default function install(vue, toastName) {
    if (Vue) {
        return
    }
    Vue = vue
    ToastConstructor = vue.extend(Tosat)

    vue.prototype['$' + toastName] = toast
}